/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.lic.system.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lic.system.common.Result;
import com.lic.system.mapper.UserTokenMapper;
import com.lic.system.oauth2.TokenGenerator;
import com.lic.system.pojo.UserToken;
import com.lic.system.service.UserTokenService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Service
public class UserTokenServiceImpl extends ServiceImpl<UserTokenMapper, UserToken> implements UserTokenService {
    //12小时后过期
    @Value("${expire.time}")
    private  Integer time;


    @Resource
    UserTokenMapper userTokenMapper;

    @Override
    public Result createToken(Integer userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + time * 1000);

        //判断是否生成过token
        UserToken tokenEntity = this.getById(userId);
        if (tokenEntity == null) {
            tokenEntity = new UserToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            this.save(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            this.updateById(tokenEntity);
        }

        Result r = Result.ok().put("token", token).put("expire", time);

        return r;
    }

    @Override
    public void logout(Integer userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        UserToken tokenEntity = new UserToken();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        this.updateById(tokenEntity);
    }


    @Override
    public UserToken queryByToken(String token) {


        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("token",token);
        return userTokenMapper.selectOne(queryWrapper);
    }

    @Override
    public Set<String> selectSetString(Integer uid) {
         Set<String>  strings  = new HashSet<>();
        return null;
    }


}
